package com.twan.base.network;

import android.app.Activity;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lxj.xpopup.core.BasePopupView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.twan.base.api.Result;
import com.twan.base.util.LogUtil;
import com.twan.base.util.SystemUtil;
import com.twan.base.util.ToastUtil;

import java.net.SocketTimeoutException;

import javax.net.ssl.SSLHandshakeException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by twan on 2017/11/10.
 */

public abstract class ZyCallBack<T> implements Callback {
    protected Result<T> mResult;
    private long mLastToastTime=0;
    protected T mData;

    @Override
    public void onResponse(Call call, Response response) {
        mResult =(Result<T>) response.body();
        dismiss();
        if (check(response)) {
            if (mResult.result == 1) {
                mData = mResult.data;
                doSuccess();
            }else {
                doFailure();
            }
        }
    }

    protected boolean check(Response response){
        if (mResult == null){
            try {
                String rbv =response.errorBody().string();
                Result err_res=new Gson().fromJson(rbv, Result.class);
                if (err_res != null) {
                    ToastUtil.error("错误代码:" + err_res.result + " ," + err_res.msg);
                }
            } catch (Exception e) {
                if (isShowError) {
                    ToastUtil.error("系统异常，无法获取错误信息");
                }
            }
            return false;
        }

        return true;
    }

    public abstract void doSuccess();
    public void doFailure(){
        ToastUtil.error("请求失败,"+mResult.msg);
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        dismiss();
        if (!SystemUtil.isNetworkConnected()){
            if (isShowError && System.currentTimeMillis() - mLastToastTime > 3000) {
                mLastToastTime = System.currentTimeMillis();
                ToastUtil.error("请检查网络");
            }
        }else {
            if (t instanceof SocketTimeoutException) {
                if (isShowError) {
                    ToastUtil.error("请求超时,请重试!");
                }
            }else if (t instanceof SSLHandshakeException) {
                if (isShowError) {
                    ToastUtil.error("请检查本机时间!");
                }
            }else if (t instanceof JsonSyntaxException){
                if (isShowError) {
                    ToastUtil.error("数据解析错误!");
                }
            }else {
                if (isShowError) {
                    LogUtil.d("请求失败:"+t.getMessage());
                    ToastUtil.error("请求失败,请重试!"+t.getMessage());
                }
                LogUtil.wtf(t.toString());
            }
        }

    }

    private RefreshLayout mRefreshLayout;
    private BasePopupView mPopup;
    private Activity activity;
    private boolean isShowError=true;//默认提示错误

    public ZyCallBack(){}

    public ZyCallBack(boolean isShowError){
        this.isShowError = isShowError;
    }

    public ZyCallBack(RefreshLayout refreshLayout){
        mRefreshLayout = refreshLayout;
    }

    public ZyCallBack(BasePopupView popupView){
        mPopup = popupView;
    }

    //没有使用刷新，则使用这个
    public ZyCallBack(Activity act, boolean showLoading){
        activity=act;
        if (showLoading && mPopup != null) {
            mPopup.show();
        }
    }

    private void dismiss(){
        if (activity != null){
            //new XPopup.Builder(activity).dis;
        }

        if (mPopup != null && !mPopup.isDismiss()){
            mPopup.dismiss();
        }
        if (mRefreshLayout != null && mRefreshLayout.isRefreshing()) {
            mRefreshLayout.finishRefresh();
        }
        if (mRefreshLayout != null && !mRefreshLayout.isLoadmoreFinished()){
            mRefreshLayout.finishLoadmore();
        }
    }
}
